package com.android.videotest.music;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 * 项目名称：VideoTest
 * 类 名 称：MusicLibrary
 * 类 描 述：MusicLibrary
 * 创建时间：2019-11-18 10:42
 * 创 建 人：sansecy
 */
public class MusicLibrary {
    private static final TreeMap<String, MediaMetadataCompat> music = new TreeMap<>();

    /**
     * 获取MediaPlayer获取播放列表
     */
    public static void initSongList(Context context) {
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                MediaMetadataCompat.Builder builder = new MediaMetadataCompat.Builder();

                String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String titleName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String albumName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                String artistName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                long songId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
                long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
//                Uri trackUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, songId);
//                String SongUri = trackUri.toString();
                //获取专辑ID
                Log.d( "-App", "initSongList: " + url);
                int albumId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                builder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, titleName);
                String mediaId = String.valueOf(songId);
                builder.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, mediaId);
                builder.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, url);
                builder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, albumName);
                builder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration);
//                builder.putLong(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, songId);
                builder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, String.valueOf(albumId));
                builder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, artistName);
                builder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, artistName);
                music.put(mediaId, builder.build());
            }
            cursor.close();
        }
        //按名称排序
//        Collections.sort(songList, (a, b) -> a.getTitle().compareTo(b.getTitle()));
//        return songList;
    }

    public static List<MediaBrowserCompat.MediaItem> getMediaItems() {
        List<MediaBrowserCompat.MediaItem> result = new ArrayList<>();
        for (MediaMetadataCompat metadata : music.values()) {
            result.add(
                    new MediaBrowserCompat.MediaItem(
                            metadata.getDescription(), MediaBrowserCompat.MediaItem.FLAG_PLAYABLE));
        }
        return result;
    }
    public static MediaMetadataCompat getMetadata(Context context, String mediaId) {
        MediaMetadataCompat metadataWithoutBitmap = music.get(mediaId);
        Bitmap albumArt = getAlbumBitmap(context, mediaId);

        // 由于MediaMetadataCompat是不可变的，因此我们需要创建一个副本来设置专辑封面。
        // 我们不会在一开始就在所有项目上都设置它，以便它们不会占用不必要的内存。
        MediaMetadataCompat.Builder builder = new MediaMetadataCompat.Builder();
        for (String key :
                new String[]{
                        MediaMetadataCompat.METADATA_KEY_TITLE,
                        MediaMetadataCompat.METADATA_KEY_MEDIA_ID,
                        MediaMetadataCompat.METADATA_KEY_MEDIA_URI,
                        MediaMetadataCompat.METADATA_KEY_ALBUM,
                        MediaMetadataCompat.METADATA_KEY_ARTIST,
                        MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI,
                        MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST
                }) {
            builder.putString(key, metadataWithoutBitmap.getString(key));
        }
        builder.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, albumArt);
        builder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, metadataWithoutBitmap.getLong(MediaMetadataCompat.METADATA_KEY_DURATION));
        return builder.build();
    }

    public static Bitmap getAlbumBitmap(Context context, String mediaId) {
        //先通过mediaId查找albumId
        MediaMetadataCompat compat = music.get(mediaId);
        String albumId = compat.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI);
        String uriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[]{"album_art"};
        Cursor cur = context.getContentResolver().query(Uri.parse(uriAlbums + "/" + albumId), projection, null, null, null);
        String album_art = null;
        if (cur != null && cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        if (cur != null) {
            cur.close();
        }
        return BitmapFactory.decodeFile(album_art);
    }

    public static TreeMap<String, MediaMetadataCompat> getMusic() {
        return music;
    }

    public static String getMusicFilePath(String mediaId) {
        MediaMetadataCompat compat = music.get(mediaId);
        return compat.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI);
    }
}
